package com.mirror.tk.api.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mirror.tk.api.common.Constant;
import com.mirror.tk.api.common.support.JwtFace;
import com.mirror.tk.api.common.support.JwtUser;
import com.mirror.tk.api.utils.JwtUtil;
import com.mirror.tk.framework.common.web.support.JsonResult;
import com.mirror.tk.framework.utils.mapper.JsonMapper;

/**
 * Jwt过滤器
 * 负责将认证信息搬运到request中，以便后续使用
 * 同时动态刷新jwt过期时间
 * by fengshi
 */
public class JwtInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 请求头认证处理
		final String authHeader = request.getHeader("Authorization");
		if (authHeader == null || !authHeader.startsWith("Bearer ")) {
			// ---------------------------------------------------------------------------
//			User user = new User();
//			user.setId(1l);
//			user.setPhone("13617635410");
//			user.setStatus(2);
//			user.setUsername("封狮");
//			request.setAttribute(JwtUser.JWT_USER_OBJECT_KEY, JwtUser.bulider(user));
			// ---------------------------------------------------------------------------
			return true;
		}
		final String jwt = authHeader.substring(7);
		if(JwtUtil.validateJwt(jwt)){
			request.setAttribute(JwtFace.CLAIMS_KEY, JwtUtil.getClaimsByJwt(jwt));
			request.setAttribute(JwtUser.JWT_USER_OBJECT_KEY, JwtUtil.getJwtUser(jwt));
			response.addHeader("Authorization", authHeader);
		} else {
			response.setCharacterEncoding("UTF-8");
			response.setStatus(HttpStatus.SC_UNAUTHORIZED);
	        PrintWriter printWriter = response.getWriter();
	        printWriter.write(JsonMapper.nonDefaultMapper().toJson(new JsonResult(Constant.Global.UNAUTHORIZED, Constant.Global.UNAUTHORIZED_MSG)));
	        printWriter.flush();
	        printWriter.close();
			return false;
		}
		// 动态刷新token过期时间
		if(JwtUtil.isOverdue(jwt)){
			response.addHeader("Authorization", "Bearer " + JwtFace.updateJwtUser(JwtUtil.getJwtUser(jwt)));
		}
		return true;
	}

}
